﻿using System;
using System.Reflection;
using System.Threading.Tasks;
using AresWebService.Tests.Console.Properties;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace AresWebService.Tests.Console
{
	class Program
	{
		static void Main(string[] args)
		{
			System.Console.WriteLine("{0} Loading assembly {1}:", DateTime.Now, Settings.Default.Assembly2test);
			var assembly = Assembly.LoadFrom(Settings.Default.Assembly2test);
			var types = assembly.GetTypes();
			foreach(var type in types)
			{
				var tatt = type.GetCustomAttribute<TestClassAttribute>();
				if (tatt == null)
					continue;
				System.Console.WriteLine("{0} Executing tests in type {1}:", DateTime.Now, type.FullName);
				var methods = type.GetMethods();
				var testobj = assembly.CreateInstance(type.FullName);
				foreach(var m in methods)
				{
					var matt = m.GetCustomAttribute<TestMethodAttribute>();
					if (matt == null)
						continue;
					try
					{
						System.Console.WriteLine("{0} Executing test {1}:", DateTime.Now,  m.Name);

						//var mdel = (AsyncMethod)Delegate.CreateDelegate(typeof(AsyncMethod), m);
						//mdel.BeginInvoke()

						var task = m.Invoke(testobj, null) as Task;
						if (task == null)
							continue;
						var aw = task.GetAwaiter();
						while(!aw.IsCompleted)
						{
							task.Wait(1000);
							System.Console.WriteLine("{0} waiting...", DateTime.Now);
						}
						task.Dispose();
						System.Console.WriteLine("{0} Done.", DateTime.Now);
						System.Console.WriteLine();
						System.Console.WriteLine();
					}
					catch (Exception ex)
					{
						System.Console.WriteLine("{0} Error: {1}", DateTime.Now, ex);
						System.Console.WriteLine();
						System.Console.WriteLine();
					}
					
				}
			}
			System.Console.WriteLine("{0} Finished.", DateTime.Now);
			System.Console.ReadLine();
		}

		delegate Task AsyncMethod();
	}
}
